package com.wzqj.agent.web.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wzqj.agent.web.dao.AgentDao;
import com.wzqj.agent.web.dao.SalesDao;
import com.wzqj.agent.web.dao.UserDao;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.Sales;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.wsp.encrypt.MD5;
/**
 * 用户业务实现层
 * @author gz
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService{
	private Logger log = LogManager.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;
	@Autowired
	private AgentDao agentDao;
	@Autowired
	private SalesDao salesDao;
	
	
	
	@Override
	public void insert(User user) {
		User isExit = userDao.getByUsername(user.getUsername());
		Integer userId = null;
		if(isExit==null){
			//密码MD5加密处理
			byte[] pwBts= user.getPassword().getBytes();
			if (pwBts!=null&&pwBts.length>0) {
				user.setPassword(MD5.getMD5(pwBts));
			}
			 userDao.insert(user);
			 userId=user.getId();
		}
	}

	@Override
	public int delete(Integer id) {
		 userDao.deleteById(id);
		 return id;
	}

	@Override
	public int update(User user) {
		 userDao.update(user);
		 return user.getId();
	}

	@Override
	public User getById(Integer id) {
		return userDao.getById(id);
	}

	@Override
	public List<User> getAll() {
		return userDao.getAll();
	}

	/**
	 * 用户登陆
	 */
	@Override
	public User login(String username, String password) {
		User user = userDao.getByUsername(username);
		if (user==null) {
			return null;
		}
		String pwDB = user.getPassword();
		//密码加密校验
		byte[] pwBts= password.getBytes();
		String pwMD5= MD5.getMD5(pwBts);
		if (!pwMD5.equals(pwDB)) {
			return null;
		}
		//校验用户对应的超级代理商或者业务员
		int type= user.getType();
		if (0==type) {
			return user;
		}
		if (1==type) {
			Agent agent = agentDao.getById(user.getTypeId());
			if (agent==null||agent.getStatus()!=1) {
				return null;
			}
			
		}
		if (2==type) {
			Sales sales = salesDao.getById(user.getTypeId());
			if (sales==null||sales.getStatus()!=1) {
				return null;
			}
		}
		return user;
	}

	@Override
	public List<User> getByRole(Integer roleId) {
		return userDao.getByRole(roleId);
	}

	@Override
	public User getByUsername(String username) {
		return userDao.getByUsername(username);
	}

	@Override
	public User getByType(Integer type,Integer typeId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		params.put("typeId", typeId);
		return userDao.getByType(params);
	}
	

}
